package com.example.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private int port;
    private ExecutorService executorService;

    public Server(int port) {
        this.port = port;
        this.executorService = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池
    }

    public void start() {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.configureBlocking(false);
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                SocketChannel clientSocket = serverSocketChannel.accept();
                if (clientSocket != null) {
                    System.out.println("客户端已连接：" + clientSocket.getRemoteAddress());
                    executorService.submit(() -> handleClient(clientSocket));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(SocketChannel clientSocket) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            while (clientSocket.read(buffer) > 0) {
                buffer.flip();
                String receivedData = new String(buffer.array(), 0, buffer.limit());
                System.out.println("收到客户端数据：" + receivedData);

                // 处理并回复客户端
                String responseData = "服务器已收到数据：" + receivedData;
                buffer.clear();
                buffer.put(responseData.getBytes());
                buffer.flip();
                clientSocket.write(buffer);
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server(8080);
        server.start();
    }
}
